package com.epfresh.supplier.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputFilter;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.epfresh.api.entity.RequestEntityMap;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.ucrop.PhotoCore;
import com.epfresh.api.universalimageloader.core.ImageLoader;
import com.epfresh.api.utils.CashierInputFilter;
import com.epfresh.api.utils.FormatUtil;
import com.epfresh.api.views.DragGridView;
import com.epfresh.api.widget.CommonInputItem;
import com.epfresh.supplier.R;
import com.epfresh.supplier.constant.Constant;
import com.epfresh.supplier.delegate.UploadProductDelegate;
import com.epfresh.supplier.dialog.ReturnReasonListDialog;
import com.epfresh.supplier.entity.ProductReturnInfo;
import com.epfresh.supplier.entity.ProductReturnInfoReasonList;
import com.epfresh.supplier.entity.StatusEntity;
import com.google.gson.Gson;

import java.util.List;

public class ReturnApplicationInfoActivity extends BaseActivity  {

    ImageView mIvProduct;
    TextView mTvProductTitle;
    TextView mTvProductPrice;
    TextView mTvReturnDescribe;
    TextView mTvProductSize;
    TextView mTvBtnCommit;

    CommonInputItem mCiReturnReason;
    CommonInputItem mCiReturnPrice;
    CommonInputItem mCiReturnNotice;
    DragGridView mDgv;
    private UploadProductDelegate upd;
    private PhotoCore photoCoreDetail;

    String orderId,jmtId;//新减免退 orderId;重新申请 jmtId;
    ProductReturnInfo mProductReturnInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if(savedInstanceState != null){
            getIntent().putExtra(Constant.TYPE,savedInstanceState.getInt(Constant.TYPE));
            getIntent().putExtra("orderId", savedInstanceState.getString("orderId"));
            getIntent().putExtra("jmtId", savedInstanceState.getString("jmtId"));
        }

        orderId = getIntent().getStringExtra("orderId");
        jmtId = getIntent().getStringExtra("jmtId");
        setContentView(R.layout.activity_return_application_info);
        initView();
        reqReturnInfo();
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putString("orderId", getIntent().getStringExtra("orderId"));
        outState.putString("jmtId", getIntent().getStringExtra("jmtId"));
        super.onSaveInstanceState(outState);
    }

    /**
     * 手动隐藏软键盘
     *
     * @param view
     */
    public static void hideSoftKeyboard(View view) {
        Context context = view.getContext();
        InputMethodManager imm = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    private void initView() {

        setToolbarTitle("申请退款");

        mIvProduct = (ImageView) findViewById(R.id.iv_product);
        mTvProductTitle = (TextView) findViewById(R.id.tv_product_title);
        mTvProductPrice = (TextView) findViewById(R.id.tv_product_price);

        mTvProductSize = (TextView) findViewById(R.id.tv_product_size);
        mTvReturnDescribe = (TextView) findViewById(R.id.tv_return_describe);
        mTvBtnCommit = (TextView) findViewById(R.id.tv_commit);
        mCiReturnReason = (CommonInputItem) findViewById(R.id.ci_return_reason);
        mCiReturnPrice = (CommonInputItem) findViewById(R.id.ci_return_price);
        mCiReturnNotice = (CommonInputItem) findViewById(R.id.ci_return_notice);
        mDgv = (DragGridView) findViewById(R.id.dgv);
        mCiReturnPrice.getEdInput().setFilters(new InputFilter[]{new CashierInputFilter()});

        mTvBtnCommit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                commit();
            }
        });

        mCiReturnReason.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideSoftKeyboard(mCiReturnPrice);
                openReasonDialog();
            }
        });

        upd = new UploadProductDelegate(this);
        if (photoCoreDetail == null) {
            photoCoreDetail = upd.getPhotoCore();
        }
        upd.setMaxLimit(3);
    }

    ReturnReasonListDialog returnReasonListDialog;

    private void openReasonDialog() {
        if (mProductReturnInfo == null) {
            return;
        }

        List<ProductReturnInfoReasonList> reasonList = mProductReturnInfo.getReasonList();

        if (reasonList == null || reasonList.size() == 0) {
            return;
        }
        if (returnReasonListDialog == null) {
            returnReasonListDialog = new ReturnReasonListDialog(this);
            returnReasonListDialog.setOnSelectedListener(new ReturnReasonListDialog.OnSelectedListener() {
                @Override
                public void onSelected(ProductReturnInfoReasonList item) {
                    if (item != null) {
                        mCiReturnReason.setTag(R.id.item_key_status, item.getCode());
                        mCiReturnReason.setContentText(item.getTitle());
                    }
                }
            });
        }
        Object tag = mCiReturnReason.getTag(R.id.item_key_status);
        String id = null;
        if (tag != null) {
            id = tag.toString();
        }
        returnReasonListDialog.show(reasonList, id);
    }

    private void commit() {


        reqSaveReturnInfo();

    }



    @Override
    public void onBackPressed() {

        if (returnReasonListDialog != null && returnReasonListDialog.isShowing()) {
            returnReasonListDialog.dismiss();
            return;
        }
        Intent back = new Intent();
        back.putExtra("orderId",orderId);
        setResult(RESULT_OK, back);
        super.onBackPressed();
    }

    @Override
    protected void onToolbarBack() {
        onBackPressed();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        photoCoreDetail.onResult(requestCode, resultCode, data);
    }

    void updateView(ProductReturnInfo productReturnInfo) {
        //最多900元，含发货运费100元
        if (productReturnInfo != null) {

            ImageLoader.getInstance().displayImage(productReturnInfo.getThumbnail(), mIvProduct);
            mTvProductTitle.setText(productReturnInfo.getProductTitle());
            mTvProductPrice.setText("单价：" + FormatUtil.subZeroAndDot(productReturnInfo.getProductPriceUnit()) + "元/" + productReturnInfo.getChargeUnit());

            mTvProductSize.setText("下单量：" + FormatUtil.subZeroAndDot(productReturnInfo.getProductCount()) + productReturnInfo.getChargeUnit());

            String s = "最多" + FormatUtil.subZeroAndDot(productReturnInfo.getTotlePrice()) + "元";
            Double freight = productReturnInfo.getFreight();
            if (freight > 0) {
                s += "，含发货运费" + FormatUtil.subZeroAndDot(freight) + "元";
            }
            mTvReturnDescribe.setText(s);


        }
    }


    private void reqSaveReturnInfo() {

      /*  appylyPrice	是	申请金额
        appleReasonType	是	原因类型
        affixsList	否	附件列表
                remark*/


        if (mProductReturnInfo == null) {
            return;
        }
        Object tag = mCiReturnReason.getTag(R.id.item_key_status);
        String appleReasonType = null;
        if (tag != null) {
            appleReasonType = tag.toString();
        }

        if (appleReasonType == null || "".equals(appleReasonType)){
            toast("请选择退款原因");
            return;
        }

        String applyPrice = mCiReturnPrice.getContentText();
        String totalPrice = FormatUtil.subZeroAndDot(mProductReturnInfo.getTotlePrice());
        if (applyPrice == null || "".equals(applyPrice)) {

            toast("请输入退款金额");
            return;
        }

        if (FormatUtil.countAdd(applyPrice,totalPrice,false) > 0){
            String s = "最多" + totalPrice + "元";
            toast(s);
            return;
        }


        String remark = mCiReturnNotice.getContentText();

        List<String> affixsList = upd.getImagesStrList();



        RequestEntityMap data = new RequestEntityMap();
        data.setCmd("pm-order/baseorder/order/jmt/save");
        data.setClientIdentifierCode(getAppApplication().getClientIdentifierCode());

/*        data.putParameter("buyerStoreId", BaseApplication.getInstance().getStoreId());
        data.putParameter("orderId", orderId);
        data.putParameter("appylyPrice", appylyPrice);
        data.putParameter("remark", remark);
        data.putParameter("affixsIds", affixsList);
        data.putParameter("remark", remark);*/
        //data.putParameter("buyerStoreId", BaseApplication.getInstance().getStoreId());
        data.putParameter("orderId", orderId);
        data.putParameter("orderJmtId", jmtId);
        data.putParameter("applyPrice", applyPrice);
        data.putParameter("remark", remark);
        StringBuffer affixsIds = new StringBuffer();
        if(affixsList!=null&&affixsList.size()>0){
            for(int i=0;i<affixsList.size();i++){
                affixsIds.append(affixsList.get(i)+",");
            }
            //String s = affixsIds.substring(0,affixsIds.length()-1);
        }
        Log.e("affixsIds",affixsIds.toString());
        data.putParameter("affixsIds", affixsIds.toString());
        data.putParameter("appleReasonType", appleReasonType);
/*

	"parameters": {
		"remark": "在一起的时候我们一起努力",
		"affixsList": ["216ec1cff1352667ff1529ad3b8e0a32.png", "4e401494ae405411ca5ceaf707f70231.png"],
		"orderJmtId": "32",
		"appleReasonType": "10",
		"applyPrice": "0.01"
	}
* */

        request(data, "pm-order/baseorder/order/jmt/save", new OnRequestListener<StatusEntity>() {
            @Override
            public StatusEntity jsonToObj(String responseStr) {
                return new Gson().fromJson(responseStr, StatusEntity.class);
            }

            @Override
            public void onFail(int failCode, Object arg, Object tag) {
                hideProgressDialog();
                mTvBtnCommit.setEnabled(true);
            }

            @Override
            public void onResponseError(int failCode, Object arg, Object tag) {
                hideProgressDialog();
                mTvBtnCommit.setEnabled(true);
            }

            @Override
            public void onStart(Object tag) {

                showProgressDialog();
                mTvBtnCommit.setEnabled(false);
            }

            @Override
            public void onResponse(ResponseEntity<StatusEntity> response, Object tag) {
                mTvBtnCommit.setEnabled(true);
                hideProgressDialog();
                if (response != null) {
                    Intent back = new Intent();
                    back.putExtra("orderId",orderId);
                    setResult(RESULT_OK, back);
                    finish();
                }
            }
        });
    }

    private void reqReturnInfo() {
        RequestEntityMap data = new RequestEntityMap();
        data.setCmd("pm-order/baseorder/order/jmt/newLoad");
        data.setClientIdentifierCode(getAppApplication().getClientIdentifierCode());

/*        data.putParameter("buyerStoreId", BaseApplication.getInstance().getStoreId());
        data.putParameter("orderId", orderId);orderJmtId*/
        data.putParameter("orderJmtId", jmtId);
        data.putParameter("orderId", orderId);


        request(data, "pm-order/baseorder/order/jmt/newLoad", new OnRequestListener<ProductReturnInfo>() {
            @Override
            public ProductReturnInfo jsonToObj(String responseStr) {
                return new Gson().fromJson(responseStr, ProductReturnInfo.class);
            }

            @Override
            public void onFail(int failCode, Object arg, Object tag) {

            }

            @Override
            public void onResponseError(int failCode, Object arg, Object tag) {

            }

            @Override
            public void onStart(Object tag) {

            }

            @Override
            public void onResponse(ResponseEntity<ProductReturnInfo> response, Object tag) {

                if (response != null) {
                    ProductReturnInfo responseElement = response.getResponseElement();
                    mProductReturnInfo = responseElement;
                    updateView(responseElement);
                }
            }
        });
    }




}
